<template>
	<w-collapse v-model="collapseVisible" contentHeight="550px" :fullScreen="fullScreen" disabled :showArrow="false" title="计划明细">
		<fx-detials-table
			ref="detailsTable"
			:disabled="disabled"
			:tableColumn="tableColumn"
			:tableValiDate="tableValiDate"
			:tableData="tableDetails"
			:tableEditColumnProp="tableEditColumnProp"
			:mainId="programDetails.id"
			:fpSaveMain="fSaveMain"
			:fpInitAddDetailsData="fpInitAddDetailsData"
			:fpSaveDetails="fpSaveDetails"
			:fpDeleteDetails="fpDeleteDetails"
			:searchProps="['materialCode', 'materialName']"
			@on-details-refresh="onDetailsRefresh"
		>
		</fx-detials-table>
	</w-collapse>
</template>
<script>
const EDIT_INPUT_TYPE = ['materialCode', 'lineCode', 'materialUnitId', 'planTotal', 'planStartDate', 'remark']
export default {
	name: 'detailsInfo',
	props: {
		fullScreen: Boolean,
		programDetails: {
			type: Object,
			default: () => {
				return {}
			}
		},
		tableDetails: {
			type: Array,
			default: () => {
				return []
			}
		},
		itemList: {
			type: Array,
			default: () => {
				return []
			}
		},
		fSaveMain: Function,
		disabled: Boolean
	},
	data () {
		return {
			collapseVisible: true,
			tableColumn: [
				{
					prop: 'materialCode',
					label: '产品编码',
					width: '150px',
					required: true,
					fxRender: this.codeRender,
					click: this.onCellClick('code')
				},
				{ prop: 'materialName', label: '产品名称', width: '150px' },
				{
					prop: 'lineCode',
					label: '工艺路线',
					width: '150px',
					required: true,
					fxRender: this.lineRender,
					click: this.onCellClick('lineCode')
				},
				{
					prop: 'materialUnitId',
					label: '生产单位',
					width: '100px',
					required: true,
					fxRender: this.unitRender,
					click: this.onCellClick('materialUnitId')
				},
				{
					prop: 'planTotal',
					label: '计划产量',
					width: '150px',
					required: true,
					fxRender: this.planTotalRender,
					click: this.onCellClick('planTotal')
				},
				{
					prop: 'actualTotal',
					label: '实际产量',
					width: '100px',
					required: true,
					formatter: this.formatterActualTotal
				},
				{
					prop: 'planStartDate',
					label: '计划开工时间',
					width: '200px',
					required: true,
					fxRender: this.planStartDateRender,
					click: this.onCellClick('planStartDate')
				},
				{
					prop: 'actualStartDate',
					label: '实际开工时间',
					width: '150px',
					required: true,
					formatter: this.formatterDate
				},
				{
					prop: 'planEndDate',
					label: '计划完工时间',
					width: '150px',
					required: true,
					formatter: this.formatterDate
				},
				{
					prop: 'actualEndDate',
					label: '实际完工时间',
					width: '150px',
					required: true,
					formatter: this.formatterDate
				},
				{
					prop: 'processingPercent',
					label: '加工进度',
					width: '120px',
					required: true,
					fxRender: this.processingPercentRender
				},
				{
					prop: 'state',
					label: '生产状态',
					width: '100px',
					required: true,
					formatter: this.stateRender
				},
				{
					prop: 'importState',
					label: '导入状态',
					width: '100px',
					required: true,
					formatter: this.importStateRender
				},
				{
					prop: 'remark',
					label: '备注',
					width: '150px',
					required: true,
					fxRender: this.reamrkRender,
					click: this.onCellClick('remark')
				}
			],
			tableEditColumnProp: EDIT_INPUT_TYPE,
			tableValiDate: [{
				columnProp: 'materialCode',
				rule (row, success, error) {
					if (!row.item.id) {
						error('产品编号不能为空')
					} else {
						success()
					}
				}
			}, {
				columnProp: 'lineCode',
				rule (row, success, error) {
					if (!row.lineInfo.id) {
						error('工艺路线不能为空')
					} else {
						success()
					}
				}
			}, {
				columnProp: 'materialUnitId',
				rule (row, success, error) {
					if (!row.itemUnit.id) {
						error('单位不能为空')
					} else {
						success()
					}
				}
			}, {
				columnProp: 'planTotal',
				rule (row, success, error) {
					if (!row.planTotal) {
						error('计划产量不能为0')
					} else {
						success()
					}
				}
			}, {
				columnProp: 'planStartDate',
				rule (row, success, error) {
					if (!row.planStartDate) {
						error('计划开始时间不能为空')
					} else {
						success()
					}
				}
			}]
		}
	},
	methods: {
		codeRender (h, { row, $index }) {
			h = this.$createElement
			const filterKeys = ['name', 'code']
			return <fx-list-cell-select-item
				ref={`materialCode-${$index}`}
				vModel={row.materialId}
				isEdit={row.isEdit}
				row={row}
				rowIndex={$index}
				columnProp='materialCode'
				cellText={row.item.code}
				selectOptionList={this.itemList}
				filterKeys={filterKeys}
				vOn:on-change={this.onCodeSelectChange}
			></fx-list-cell-select-item>
		},
		onCodeSelectChange (item, row) {
			row.item = item
			row.itemUnitList = item.technologyMaterialUnitEntirys
			row.itemUnit = item.technologyMaterialUnitEntirys.find(item => {
				return item.unitType === 1
			}) || {}
			row.materialName = item.name
			row.materialId = item.id
			row.lineList = item.technologyLineEntirys || []
			row.lineInfo = item.technologyLineEntirys ? item.technologyLineEntirys[0] : {}
			const routeList = (row.lineInfo && row.lineInfo.technologyRoutingEntirys) || []
			this.renderEndDate(routeList, row)
		},
		lineRender (h, { row, $index }) {
			h = this.$createElement
			const optionProp = {
				key: 'id',
				label: 'code',
				value: 'id'
			}
			return <fx-list-cell-select
				ref={`lineCode-${$index}`}
				value={row.lineInfo.id}
				isEdit={row.isEdit}
				row={row}
				rowIndex={$index}
				columnProp='lineCode'
				cellText={row.lineInfo.code}
				selectOtionProp={optionProp}
				selectOptionList={row.lineList}
				vOn:on-change={this.onLineSelectChange}
			></fx-list-cell-select>
		},
		onLineSelectChange (item, row) {
			row.lineId = item.id
			row.lineInfo = {
				code: item.code,
				id: item.id
			}
			const routeList = item.technologyRoutingEntirys
			this.renderEndDate(routeList, row)
		},
		renderEndDate (routeList, row) {
			let totalSecond = 0
			routeList.forEach(r => {
				// 小时
				if (r.timeUnit === 1) {
					totalSecond += this.$fxUtils.h2ms(r.workTimeCount)
				}
				// 分钟
				if (r.timeUnit === 2) {
					totalSecond += this.$fxUtils.m2ms(r.workTimeCount)
				}
				// 天
				if (r.timeUnit === 3) {
					totalSecond += this.$fxUtils.d2ms(r.workTimeCount)
				}
			})
			row.totalSecond = totalSecond
			const endTime = new Date(row.planStartDate).getTime() + totalSecond
			row.planEndDate = this.$fxUtils.setDateTime(new Date(endTime), '时分')
			row.actualEndDate = this.$fxUtils.setDateTime(new Date(endTime), '时分')
		},
		unitRender (h, { row, $index }) {
			h = this.$createElement
			const optionProp = {
				key: 'id',
				label: 'busUnit',
				value: 'id'
			}
			return <fx-list-cell-select
				ref={`materialUnitId-${$index}`}
				value={row.itemUnit.id}
				isEdit={row.isEdit}
				row={row}
				rowIndex={$index}
				columnProp='materialUnitId'
				cellText={row.itemUnit.busUnit}
				selectOptionList={row.itemUnitList}
				selectOtionProp={optionProp}
				vOn:on-change={this.onUnitSelectChange}
			></fx-list-cell-select>
		},
		onUnitSelectChange (item, row) {
			const oldItem = row.itemUnitList.find(unit => {
				return unit.id === row.itemUnit.id
			}) || {}
			row.planTotal = row.planTotal * item.conversionFactor / oldItem.conversionFactor
			row.itemUnit = item
		},
		planTotalRender (h, { row, $index }) {
			h = this.$createElement
			return <fx-list-cell-input-number
				ref={`planTotal-${$index}`}
				vModel={row.planTotal}
				isEdit={row.isEdit}
				row={row}
				rowIndex={$index}
				columnProp='planTotal'
				placeholder='请输入计划产量'
				cellText={this.planTotalText(row)}
				pointSize='2'
				// vOn:on-change={this.planTotalChange}
			>
			</fx-list-cell-input-number>
		},
		planTotalText (row) {
			return row.planTotal || 0
		},
		// planTotalChange (item, row) {
		// 	row.actualTotal = item
		// },
		// 计划开始时间
		planStartDateRender (h, { row, $index }) {
			h = this.$createElement
			return <fx-list-cell-date
				ref={`planStartDate-${$index}`}
				vModel={row.planStartDate}
				isEdit={row.isEdit}
				row={row}
				rowIndex={$index}
				columnProp='planStartDate'
				cellText={this.formatterDate(row, 'planStartDate')}
				vOn:on-change={this.planStartDateChange}
			>
			</fx-list-cell-date>
		},
		planStartDateChange (item, row) {
			const endTime = new Date(row.planStartDate).getTime() + row.totalSecond
			row.planEndDate = this.$fxUtils.setDateTime(new Date(endTime), '时分')
			row.actualEndDate = this.$fxUtils.setDateTime(new Date(endTime), '时分')
			row.actualStartDate = item
		},
		// 加工进度
		processingPercentRender (h, { row }) {
			return <el-progress percentage={Math.round(row.actualTotal / row.planTotal) || 0}
			></el-progress>
		},
		// 备注
		reamrkRender (h, { row, $index }) {
			h = this.$createElement
			return <fx-list-cell-input
				ref={`remark-${$index}`}
				vModel={row.remark}
				isEdit={row.isEdit}
				row={row}
				rowIndex={$index}
				placeholder='请输入备注'
				columnProp='remark'
			>
			</fx-list-cell-input>
		},
		// 生产状态
		stateRender (row) {
			switch (row.state) {
			case 0:
				return '未开始'
			case 1:
				return '进行中'
			case 2:
				return '已完工'
			default:
				return ''
			}
		},
		// 导入状态
		importStateRender (row) {
			switch (row.importState) {
			case 0:
				return '未导入'
			case 1:
				return '已导入'
			default:
				return ''
			}
		},
		formatterActualTotal (row) {
			return row.actualTotal || 0
		},
		onCellClick (type) {
			return (row) => {
				this.$refs.detailsTable.setRowEdit(row, type)
			}
		},
		fpInitAddDetailsData () {
			return new Promise(resolve => {
				resolve({
					itemUnitList: [],
					lineList: [],
					materialId: '',
					materialName: '',
					item: {},
					itemUnit: {},
					lineInfo: {},
					planTotal: 0,
					actualTotal: 0,
					totalSecond: 0,
					planStartDate: this.$fxUtils.setDateTime(new Date(), '时分'),
					actualStartDate: this.$fxUtils.setDateTime(new Date(), '时分'),
					planEndDate: '',
					actualEndDate: '',
					processingPercent: 0,
					state: 0,
					importState: 0,
					remark: ''
				})
			})
		},
		checkDetailsUnSaving () {
			return this.$refs.detailsTable.checkDetailsUnSaving()
		},
		formatterDate (row, prop) {
			if (row[prop]) {
				return this.$fxUtils.setDateTime(new Date(new Date(row[prop]).getTime()), 'noSecond')
			} else {
				if (prop === 'actualStartDate') {
					return this.$fxUtils.setDateTime(new Date(new Date(row[prop] || row.planStartDate).getTime()), 'noSecond')
				}
				if (prop === 'actualEndDate') {
					if (row[prop] === '' && row.planEndDate === '') {
						return ''
					}
					return this.$fxUtils.setDateTime(new Date(new Date(row[prop] || row.planEndDate).getTime()), 'noSecond')
				}
			}
		},
		fpSaveDetails (detail) {
			detail.productionPlanId = this.programDetails.id
			return this.onSaveDetailsHandler(detail)
		},
		onSaveDetailsHandler (params) {
			const { id, materialId, planTotal, planStartDate, planEndDate, productionPlanId, remark } = params
			const filterParam = {
				id,
				materialId,
				lineId: params.lineInfo.id,
				materialUnitId: params.itemUnit.id,
				planTotal,
				planStartDate,
				planEndDate,
				productionPlanId,
				remark
			}
			return this.$fxApi('schedule.saveOrUpdatePlanDetail')({ data: filterParam }).then(res => {
				return Promise.resolve(res)
			})
		},
		fpDeleteDetails (ids) {
			if (ids.length > 0) {
				return this.$fxApi('schedule.detailBatchDelete')({
					data: {
						ids: ids
					}
				}).then(res => {
					return Promise.resolve(res)
				})
			}
		},
		onDetailsRefresh () {
			this.$emit('on-details-refresh')
		}
	}
}
</script>
<style lang="stylus" scoped>
@import '~$assets/stylus/varsty.styl'
</style>
